package com.ishopping.web.manage.filter;

import javax.servlet.ServletRequest;
import javax.servlet.ServletResponse;

import com.ishopping.api.manage.entity.LoginToken;
import org.apache.shiro.authc.AuthenticationToken;
import org.apache.shiro.web.filter.authc.FormAuthenticationFilter;
import org.apache.shiro.web.util.WebUtils;

/**
 * 自定义FormAuthenticationFilter，认证之前实现验证码校验
 */
public class LoginFormAuthenticationFilter extends FormAuthenticationFilter {

	public static final String DEFAULT_CAPTCHA_PARAM = "captcha";

	public String getCaptchaParam() {
		return DEFAULT_CAPTCHA_PARAM;
	}

	/**
	 * 获取验证码
	 * @param request
	 * @return String
	 */
	protected String getCaptcha(ServletRequest request) {
		return WebUtils.getCleanParam(request, getCaptchaParam());
	}

	/**
	 * 创建令牌对象, 加入验证码
	 * @param request
	 * @param response
	 * @return AuthenticationToken
	 */
	protected AuthenticationToken createToken(ServletRequest request, ServletResponse response) {
		String username = getUsername(request);
		String password = getPassword(request);
		String captcha = getCaptcha(request);
		boolean rememberMe = isRememberMe(request);
		String host = getHost(request);
		return new LoginToken(username, password.toCharArray(), rememberMe, host, captcha);
	}
}
